import { defineStore } from 'pinia'
import { apiClient } from '@/utils/api-client'
import { useAuthStore } from './auth'

export interface Bookmark {
  id: string
  userId: string
  title: string
  url: string
  iconUrl?: string
  category?: string
  sortOrder?: number
  createdAt: string
  updatedAt: string
}

interface BookmarksState {
  bookmarks: Bookmark[]
  loading: boolean
}

export const useBookmarksStore = defineStore('bookmarks', {
  state: (): BookmarksState => ({
    bookmarks: [],
    loading: false
  }),

  getters: {
    sortedBookmarks: (state) => {
      return [...state.bookmarks].sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
    }
  },

  actions: {
    // 获取用户书签
    async fetchBookmarks() {
      const authStore = useAuthStore()
      if (!authStore.user) return

      try {
        this.loading = true
        const response = await apiClient.getBookmarks()
        this.bookmarks = response.bookmarks || []
      } catch (error) {
        console.error('获取书签失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 添加书签
    async addBookmark(bookmark: Omit<Bookmark, 'id' | 'userId' | 'createdAt' | 'updatedAt'> & { icon?: string | null }) {
      const authStore = useAuthStore()
      if (!authStore.user) return false

      try {
        // 获取图标URL - 优先使用自定义图标，否则使用网站favicon
        const iconUrl = bookmark.icon !== null && bookmark.icon !== undefined 
          ? bookmark.icon 
          : this.getFaviconUrl(bookmark.url)
        
        const response = await apiClient.createBookmark({
          title: bookmark.title,
          url: bookmark.url,
          iconUrl: iconUrl,
          category: bookmark.category || 'default'
        })

        // 重新获取书签列表以更新本地状态
        await this.fetchBookmarks()
        return true
      } catch (error) {
        console.error('添加书签失败:', error)
        return false
      }
    },

    // 更新书签
    async updateBookmark(id: string, updates: Partial<Bookmark> & { icon?: string | null }) {
      try {
        // 处理图标URL
        const updateData: any = { ...updates }
        if ('icon' in updates) {
          updateData.iconUrl = updates.icon !== null && updates.icon !== undefined 
            ? updates.icon 
            : this.getFaviconUrl(updates.url || '')
          delete updateData.icon
        }
        
        const response = await apiClient.updateBookmark(id, updateData)

        // 重新获取书签列表以更新本地状态
        await this.fetchBookmarks()
        return true
      } catch (error) {
        console.error('更新书签失败:', error)
        return false
      }
    },

    // 删除书签
    async deleteBookmark(id: string) {
      try {
        await apiClient.deleteBookmark(id)

        // 重新获取书签列表以更新本地状态
        await this.fetchBookmarks()
        return true
      } catch (error) {
        console.error('删除书签失败:', error)
        return false
      }
    },

    // 获取网站图标URL
    getFaviconUrl(url: string): string {
      try {
        const domain = new URL(url).hostname
        return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`
      } catch {
        return '/favicon.ico'
      }
    },

    // 更新书签排序
    async updateBookmarkOrder(updatedBookmarks: Bookmark[]) {
      try {
        // 批量更新书签排序
        const updates = updatedBookmarks.map(bookmark => ({
          id: bookmark.id,
          sortOrder: bookmark.sortOrder || 0
        }))
        
        await apiClient.updateBookmarkOrder(updates)
        
        // 重新获取书签列表以更新本地状态
        await this.fetchBookmarks()
        return true
      } catch (error) {
        console.error('更新书签排序失败:', error)
        throw error
      }
    },

    // 清除书签数据
    clearBookmarks() {
      this.bookmarks = []
    }
  }
})